package utils

import (
	"crypto/md5"
	"fmt"
	"io/ioutil"
	"regexp"
	"strings"

	"github.com/ErikDubbelboer/gspt"
)

// MD5 获取md5字符串
func MD5(key string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(key)))
}

// BytesFromFile 从文件中读取字节
func BytesFromFile(filePath string) ([]byte, error) {
	bytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		fmt.Println("bytesFromFile:", err.Error())
		return nil, err
	}
	return bytes, nil
}

// RegexText 从字符串中获取匹配的内容
func RegexText(reg string, content string) string {
	regex, err := regexp.Compile(reg)
	if err != nil {
		return content
	}
	regexStrs := regex.FindAllString(content, 1)
	if len(regexStrs) > 0 {
		return strings.TrimSpace(regexStrs[0])
	}
	return ""
}

// SetProcessName https://github.com/ErikDubbelboer/gspt
func SetProcessName(title string) error {
	length := len(title)
	if length >= 255 {
		length = 255
		gspt.SetProcTitle(title[:255])
	} else {
		title += strings.Repeat(" ", 255-length)
		gspt.SetProcTitle(title)
	}
	gspt.SetProcTitle(title)
	return nil
}
